<?php 
namespace App\Services;
use App\Models\Cart;
use Auth;
use Cookie;
use App\Models\Goods;

class CartService {

    public function getCarts()
    {
        $user = Auth::user();
        if($user)
        {
            return $carts = $user->carts()->with('goods')->get();
        }
        $cookieCarts = Cookie::get('carts');
        if(!empty($cookieCarts))
        {
            $data = json_decode($cookieCarts, true);
            $ids = array_keys($data);
            $goods = Goods::find($ids)->pluck(null, 'id');

            foreach($data as $k => &$v)
            {
                if(!empty($goods[$k]))
                {
                    $v['goods'] = $goods[$k];
                }
                $v = (object)$v;
            }
            unset($v);
            return $data;
        }
        return false;
    }

	public function createCart($data)
	{
		$user = Auth::user();
		if($user)
    	{
    		$carts = $user->carts()->where('goods_id', $data['goods_id'])->first();
    		if($carts)
    		{
    			return $carts->increment('quantity', $data['quantity']);
    		}
    		return $user->carts()->create($data);
    	}

    	return $this->setCookieCart($data);
	}

    public function removeCart($goods_id) {
        $user = Auth::user();
        if($user) {
            return $user->carts()->where('goods_id', $goods_id)->delete();
        }
        $data = json_decode(Cookie::get('carts'), true);

        // $carts = array_filter($data, function($item) use($goods_id) {
        //     return $item['goods']['id'] != $goods_id;
        // });
    }

	protected function setCookieCart($data)
	{
		$carts = Cookie::get('carts');
    	if($carts)
    	{
    		$carts = json_decode($carts, true);
    		if(isset($carts[$data['goods_id']]))
    		{
    			$carts[$data['goods_id']]['quantity'] += $data['quantity'];
    			Cookie::queue('carts', json_encode($carts), 3600 * 24 * 7);
    			return true;
    		}
    	}

    	$carts[$data['goods_id']] = $data;
    	Cookie::queue('carts', json_encode($carts), 3600 * 24 * 7);
    	return true;
	}
}